import React, {useEffect, useState} from 'react';
import {Button, Form, Input, Modal, Table, TableProps} from 'antd';
import type {Building} from "@/types/resp/building";
import buildingApi from '@/api/buildingApi'
import {Result} from "@/types/result";
import {Page} from "@/types/page";


interface BuildingSelectorProps {
  visible: boolean;
  onBuildingSelected: (selectedBuilding: { buildingId?: number; buildingName?: string; }) => void;
  onCloseBuildingSelector: () => void;
}

const BuildingSelector: React.FC<BuildingSelectorProps> = ({visible, onBuildingSelected, onCloseBuildingSelector}) => {

  const [buildingSelectorForm] = Form.useForm();

  const onFinish = async () => {
    await onSearch()
  };

  const onReset = () => {
    buildingSelectorForm.resetFields();
  };

  const [data, setData] = useState<Building[]>([]);
  const onSearch = async () => {
    try {
      const resp: Result<Page<Building>> = await buildingApi.find(buildingSelectorForm.getFieldsValue())
      if (resp && resp.code === 1) {
        if (resp.data) {
          const page: Page<Building> = resp.data
          if (page && page.list.length > 0) {
            setData(page.list)
          }
        }
      }
    } catch (e) {
      console.log('获取数据异常', e)
    }
  };

  const columns: TableProps<Building>['columns'] = [
    {title: '楼栋名称', dataIndex: 'buildingName', key: 'buildingName'},
    {title: '地址', dataIndex: 'address', key: 'address'},
    {title: '楼层层数', dataIndex: 'floorCount', key: 'floorCount'},
    {title: '楼栋户数', dataIndex: 'roomCount', key: 'roomCount'},
  ];

  const handleRowDoubleClick = (row: Building) => {
    onBuildingSelected({
      buildingId: row.id,
      buildingName: row.buildingName,
    })
  };

  const selectorFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onCloseBuildingSelector}>关闭</Button>
    </div>
  );

  useEffect(() => {
    if (visible) {
      onSearch();
    }
  }, [visible]);


  return (
    <Modal title={"楼栋信息选择器(双击行选中)"} open={visible} onCancel={onCloseBuildingSelector}
        width={'var(--modal-width)'} footer={selectorFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      <Form form={buildingSelectorForm} onFinish={onFinish} layout={"inline"}>
        <Form.Item name="buildingName" label="楼栋名称">
          <Input maxLength={100} placeholder="请输入楼栋名称"/>
        </Form.Item>
        <Form.Item name="address" label="地址">
          <Input maxLength={255} placeholder="请输入地址"/>
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">查询</Button>
        </Form.Item>
        <Form.Item label={null}>
          <Button onClick={onReset}>重置</Button>
        </Form.Item>
      </Form>
      <Table<Building> columns={columns} dataSource={data} size="small" rowKey={record => record.id}
                         pagination={{ position: ["bottomCenter"] }}
                         onRow={(row) => ({
                           onDoubleClick: (event) => {
                             event.preventDefault();
                             handleRowDoubleClick(row);
                           },
                         })}/>
    </Modal>
  );
};

export default BuildingSelector;
